import json

import common

tag = "News"
fields = ["Content", "Pinlun"]
server = common.ServerDebug

def list_news():
    last_index = 0
    has_more = True
    page_index = 1
    while has_more:
        data = {
            "fields": fields,
            "pageIndex": page_index,
            "lastIndex": last_index,
            "pageSize": 200,
        }
        data = json.dumps(data, ensure_ascii=False)
        response_data = common.page(tag, data, server=server)
        arm = json.loads(response_data)
        last_index = arm['data']['lastIndex']
        has_more = len(arm['data']['data']) >= 200
        for record in arm['data']['data']:
            print(record)
        page_index += 1

def add_pl(rec_id:str, content:str):
    actions = []
    actions.append({
        'action': 11,
        'tag': fields[1],
        '_id': int(rec_id),
        'fv': content
    })
    edit_message = {'actions': actions}
    edit_message = json.dumps(edit_message, ensure_ascii=False)
    common.batch_modify(tag, edit_message, server=server)

def remove_pl(rec_id:str, content:str):
    actions = []
    actions.append({
        'action': 254,
        'tag': fields[1],
        '_id': int(rec_id),
        'fv': content
    })
    edit_message = {'actions': actions}
    edit_message = json.dumps(edit_message, ensure_ascii=False)
    common.batch_modify(tag, edit_message, server=server)

def change_pl(rec_id:str, idx:int, content:str):
    actions = []
    actions.append({
        'action': 21,
        'tag': fields[1],
        '_id': int(rec_id),
        'id': idx,
        'fv': content
    })
    edit_message = {'actions': actions}
    edit_message = json.dumps(edit_message, ensure_ascii=False)
    common.batch_modify(tag, edit_message, server=server)

if __name__ == "__main__":
    # list_news()
    # add_pl('38963753636868','AABBC')
    # remove_pl('38963753636868','AABBC')
    change_pl('38963753636868',4,'新闻标题已成艺术AA')
